package com.fenghongzhang.login;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.regex.Pattern;


/**
 * A simple {@link Fragment} subclass.
 */
public class RegisterFragment extends Fragment {
    private EditText registerName;
    private EditText registerPwd;
    private Button register;

    private SQLiteDatabase db;
    public RegisterFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_register, container, false);

        MySqlHelper mySqlHelper = new MySqlHelper(getActivity(), "user.db", null, 1);
         db = mySqlHelper.getReadableDatabase();


        registerName = (EditText) inflate.findViewById(R.id.register_name);
        registerPwd = (EditText) inflate.findViewById(R.id.register_pwd);
        register = (Button) inflate.findViewById(R.id.register);

        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = registerName.getText().toString();
                String pwd = registerPwd.getText().toString();

                //插入到数据库
                String reg = "^[A-Z0-9a-z]{12,18}$";
                boolean n = Pattern.matches(reg, name);
                boolean p = Pattern.matches(reg, pwd);
                if(n && p){
                    //操作数据库
//                    Log.i(TAG, "onClick: ");
                    ContentValues contentValues = new ContentValues();
                    contentValues.put("username",name);
                    contentValues.put("pwd",pwd);
                    db.insert("user",null,contentValues);
                    Toast.makeText(getActivity(), "注册成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(getActivity(),"用户名或者不合适", Toast.LENGTH_SHORT).show();
                }

//                Cursor user = db.query("user", null, null, null, null,null,null);
//                if(user != null){
//                    while(user.moveToNext()){
//                        String username = user.getString(user.getColumnIndex("username"));
//                        Toast.makeText(getActivity(), username, Toast.LENGTH_SHORT).show();
//                    }
//                }
            }
        });
        return inflate;
    }
}
